const fs = require('fs');
const UglifyJS = require("uglify-js");
class FileListPlugin {
	constructor (params) {
		this.path = params.path;
	}
	apply(compiler) {
		let _this = this;
		compiler.hooks.emit.tapAsync('FileListPlugin', (compilation, callback) => {
			let pre = compiler.context.split(/\/|\\/);
			let base = pre[pre.length - 1];
			let depFile = [];
			let reg = `^(.*${base})`;
			depFile = Array.from(compilation.fileDependencies).filter(item => !item.includes('node_modules')).map(item => {
				return item.replace(new RegExp(reg, 'g'), base).split(/\/|\\/);
			});

			let fileObjTree = {};
			//转换成树形
            function toTree(arr) {
                function init (obj, key, file) {
					if (!obj[key]) {
						obj[key] = {}
					}

					return obj[key];
                }
                for (let i = 0; i < arr.length; i++){
                    let inner = fileObjTree;
                    for (let j = 0; j < arr[i].length; j++){
                        inner = init(inner, arr[i][j]);
                    }
                }
            }

			toTree(depFile);
			fs.writeFile('dist/abc.json', JSON.stringify(fileObjTree, null, 4), (err) => {
				if (err) throw err;
				console.log('文件已被保存');
			});
			callback();
		});
	}
}
	
module.exports = FileListPlugin;
